package com.hengyue.security.service;

import com.hengyue.common.enums.UserStatus;
import com.hengyue.common.utils.StringUtils;
import com.hengyue.exception.ServiceException;
import com.hengyue.security.modle.LoginUser;
import com.hengyue.system.domain.entity.SysUser;
import com.hengyue.system.service.ISysPermissionService;
import com.hengyue.system.service.ISysUserService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("userDetailsService")
@Slf4j
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {


    private final ISysUserService sysUserService;
    private final ISysPermissionService permissionService;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("用户不存在");
        } else if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("登录用户被被删除");
        } else if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("用户被禁用");
        }

        return createLoginUser(sysUser);
    }

    public UserDetails createLoginUser(SysUser user)
    {
       /* Long deptId = null;
        if (user.getDept() != null) {
            deptId = user.getDept().getId();
        }*/
        return new LoginUser(user.getId(), null, user, permissionService.getMenuPermission(user));
    }
}


